﻿import CryptoJS from 'crypto-js'

// 生成随机字符串
const getNonceStr = function (type) {
  // CryptoJS.enc.Hex // 16进制
  // CryptoJS.enc.Utf8 // Utf8
  type = type || CryptoJS.enc.Hex
  return CryptoJS.lib.WordArray.random(128 / 8).toString(type)
}
// 加密的方法
const encryptAES = function (encryptObj, secretKey) {
  // 加密的api方法(解密时,秘钥和后面的参数配置需对应)
  // CryptoJS.AES.encrypt('待加密的字符串', '加密秘钥', {
  //   iv: CryptoJS.enc.Utf8.parse('ABCDEF1234123412'), // 十六位十六进制数作为密钥偏移量
  //   mode: CryptoJS.mode.CBC, // 支持的模式CBC/CFB/CTR//OFB/ECB
  //   padding: CryptoJS.pad.Pkcs7 // 填充方案Pkcs7/Iso97971/AnsiX923/Iso10126/ZeroPadding/NoPadding
  // })
  if (!encryptObj || !secretKey) {
    return null
  }
  let encryptedString = null
  let iv_hex_md5 = CryptoJS.MD5(secretKey).toString(CryptoJS.enc.Hex) // 秘钥进行MD5加密并转换成16进制
  let iv = iv_hex_md5.substr(8, 16)
  let secretKey_hex_md5 = iv_hex_md5.substr(0, 16)
  if (typeof encryptObj === 'string') {
    encryptedString = CryptoJS.AES.encrypt(encryptObj, CryptoJS.enc.Utf8.parse(secretKey_hex_md5), {
      iv: CryptoJS.enc.Utf8.parse(iv),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    }).toString()
  } else if (typeof encryptObj === 'object') {
    let dataString = JSON.stringify(encryptObj)
    encryptedString = CryptoJS.AES.encrypt(dataString, CryptoJS.enc.Utf8.parse(secretKey_hex_md5), {
      iv: CryptoJS.enc.Utf8.parse(iv),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    }).toString()
  }
  return encryptedString
}
// 解密的方法
const decryptAES = function (decryptObj, secretKey) {
  if (!decryptObj || !secretKey) {
    return null
  }
  let decryptedString = null
  let iv_hex_md5 = CryptoJS.MD5(secretKey).toString(CryptoJS.enc.Hex) // 秘钥进行MD5加密并转换成16进制
  let iv = iv_hex_md5.substr(8, 16)
  let secretKey_hex_md5 = iv_hex_md5.substr(0, 16)
  let bytesObj = CryptoJS.AES.decrypt(decryptObj, CryptoJS.enc.Utf8.parse(secretKey_hex_md5), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  decryptedString = bytesObj.toString(CryptoJS.enc.Utf8)
  return decryptedString
}
const getMD5String = function (str) {
  return CryptoJS.MD5(str).toString().toUpperCase()
}
export default {getNonceStr, encryptAES, decryptAES, getMD5String}
